import Mock from "mockjs";

// get从config.url中获取  post从config.body获取
function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return;
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
}

let List = [];
const count = 200;
for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock("@county(true)"),
      "age|18-60": 1,
      birth: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1),
    })
  );
}
export default {
  getUserList: (config) => {
    const { name, page = 1, limit = 10 } = param2Obj(config.url);
    console.log("name:" + name, "page:" + page, "limit:" + limit);
    const mockList = List.filter((user) => {
      if (
        name &&
        name.indexOf(',"type":"pager"') == -1 &&
        user.name.indexOf(name) === -1 &&
        user.addr.indexOf(name) === -1
      ) {
        return false;
      }
      return true;
    });
    const pageList = mockList.filter(
      (item, index) => index < limit * page && index >= limit * (page - 1)
    );
    return {
      code: 200,
      count: mockList.length,
      List: pageList,
    };
  },

  createUser: (config) => {
    const { name, addr, sex, age, birth } = JSON.parse(config.body);
    List.unshift({
      id: Mock.Random.guid(),
      name,
      addr,
      sex,
      age,
      birth,
    });
    return {
      code: 200,
      data: {
        message: "创建成功!",
      },
    };
  },
  updateUser: (config) => {
    const { id, name, addr, sex, age, birth } = JSON.parse(config.body);
    const sex_num = parseInt(sex);
    List.some((u) => {
      if (id === u.id) {
        (u.name = name),
          (u.addr = addr),
          (u.sex = sex_num),
          (u.age = age),
          (u.birth = birth);
        return true;
      }
      return {
        code: 200,
        data: {
          message: "编辑成功!",
        },
      };
    });
  },
  deleteUser: (config) => {
    const { id } = param2Obj(config.url);
    if (!id) {
      return {
        code: 500,
        message: "参数不正确!",
      };
    } else {
      List = List.filter((u) => u.id !== id);
      return {
        code: 200,
        message: "删除成功!",
      };
    }
  },
};
